<template>
  <div class="user-center-container">
    <el-card class="user-profile-card">
      <!-- 用户头像区域 -->
      <div class="avatar-section">
        <el-image
          class="user-avatar"
          :src="userInfo.avatar"
          :preview-src-list="[userInfo.avatar]"
          hide-on-click-modal
          fit="cover"
        >
          <template #error>
            <div class="avatar-error">
              <el-icon :size="50"><User /></el-icon>
            </div>
          </template>
        </el-image>

        <el-upload
          class="avatar-uploader"
          :show-file-list="false"
          :http-request="handleAvatarChange"
          accept="image/*"
        >
          <el-button type="primary" round>
            <el-icon><Upload /></el-icon>
            更换头像
          </el-button>
        </el-upload>
      </div>

      <!-- 用户基本信息 -->
      <div class="user-info-section">
        <h1 class="user-name">
          {{ userInfo.username }}
          <el-tooltip content="修改用户名" placement="top">
            <el-icon class="edit-icon" @click="editInfo = true">
              <Edit />
            </el-icon>
          </el-tooltip>
        </h1>

        <div class="user-meta">
          <el-tag type="success" round>
            <span style="display: flex; align-items: center">
              <el-icon>
                <VendorIcon />
              </el-icon>
              <!-- <Tag
                v-if="userInfo.accountType === 1"
                name="独立游戏作者"
                color="#9b59b6"
              >
                <VendorIcon />
              </Tag>
              <Tag
                v-else="userInfo.accountType === 2"
                name="游戏开发商"
                color="#3375b9"
              >
                <VendorIcon />
              </Tag> -->
              {{ accountTypeText }}
            </span>
          </el-tag>

          <div class="meta-item">
            <el-icon><Calendar /></el-icon>
            <span>注册时间: {{ formatDate(userInfo.createTime) }}</span>
          </div>

          <div class="meta-item">
            <el-icon><Refresh /></el-icon>
            <span>最后更新: {{ formatDate(userInfo.updateTime) }}</span>
          </div>
        </div>
      </div>

      <!-- 账户信息卡片 -->
      <el-card class="account-card" shadow="never">
        <template #header>
          <div class="card-header">
            <el-icon><AdminIcon /></el-icon>
            <span>账户信息</span>
          </div>
        </template>

        <div class="account-info">
          <div class="info-item">
            <span class="label">账号:</span>
            <span class="value">{{ userInfo.account }}</span>
            <el-icon
              v-if="userInfo.account"
              class="edit-icon"
              @click="editInfo = true"
            >
              <Edit />
            </el-icon>
          </div>

          <div class="info-item">
            <span class="label">邮箱:</span>
            <span class="value">{{
              userInfo.email ? userInfo.email : "未绑定"
            }}</span>
            <el-icon
              v-if="userInfo.email"
              class="edit-icon"
              @click="editInfo = true"
            >
              <Edit />
            </el-icon>
            <el-button v-else @click="editInfo = true"> 绑定邮箱 </el-button>
          </div>

          <div class="info-item">
            <span class="label">手机:</span>
            <span class="value">{{
              userInfo.telephone ? userInfo.telephone : "未绑定"
            }}</span>
            <el-icon
              v-if="userInfo.telephone"
              class="edit-icon"
              @click="editInfo = true"
            >
              <Edit />
            </el-icon>
            <el-button v-else @click="editInfo = true"> 绑定手机 </el-button>
          </div>
        </div>
      </el-card>
      <section class="editInfo">
        <el-button type="primary" @click="editInfo = true">
          修改账号信息
        </el-button>
        <el-button type="danger" @click="changePasswordVisible = true"
          >修改账户密码</el-button
        >
      </section>
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog v-model="editInfo" title="修改用户信息" width="30%">
      <el-form label-position="right" label-width="70px">
        <el-form-item label="账号">
          <el-input v-model="newUserInfo.account" />
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="newUserInfo.username" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="newUserInfo.email" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="newUserInfo.telephone" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span>
          <el-button
            @click="
              editInfo = false;
              newUserInfo = { ...userInfo, password: null };
            "
            >取消</el-button
          >
          <el-button type="primary" @click="confirmPasswordVisible = true">
            确认修改
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 确认密码对话框 -->
    <el-dialog
      text-align="center"
      title="请输入确认密码"
      v-model="confirmPasswordVisible"
      width="30%"
    >
      <el-form>
        <el-form-item label="确认密码">
          <el-input type="password" v-model="confirmPassword" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span>
          <el-button
            @click="(confirmPasswordVisible = false), (confirmPassword = '')"
            >取消</el-button
          >
          <el-button type="primary" @click="updateUserInfo">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改密码对话框 -->
    <el-dialog
      text-align="center"
      title="修改账户密码"
      v-model="changePasswordVisible"
      width="30%"
    >
      <el-form label-position="right" label-width="90px">
        <el-form-item label="旧密码">
          <el-input type="password" v-model="confirmPassword" />
        </el-form-item>
        <el-form-item label="新密码">
          <el-input type="password" v-model="newUserInfo.password" />
        </el-form-item>
        <el-form-item label="确认新密码">
          <el-input type="password" v-model="confirmNewPassword" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span>
          <el-button
            @click="
              changePasswordVisible = false;
              confirmPassword = '';
              newUserInfo.password = null;
              confirmNewPassword = '';
            "
            >取消</el-button
          >
          <el-button type="primary" @click="changePassword">确认修改</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { Edit, Upload, User, Calendar, Refresh } from "@element-plus/icons-vue";
import {
  getUserInfoApi,
  updateUserInfoApi,
  logoutApi,
  confirmPasswordApi,
} from "@/apis/user";
import { uploadApi } from "@/apis/upload";
import { ElMessage } from "element-plus";
import VendorIcon from "@/assets/svg/vendorIcon.svg";
import AdminIcon from "@/assets/svg/vendorIcon.svg";
import router from "@/router";
import { useTokenStore } from "@/store/user";
// import Tag from "@/components/tag/index.vue";
// import Tag from "@/components/tag/index.vue";

const userInfo = ref({
  id: "",
  username: "",
  account: "",
  avatar: "",
  accountType: 0,
  email: "",
  telephone: "",
  createTime: "",
  updateTime: "",
});

const newUserInfo = ref({
  id: "",
  account: "",
  username: "",
  avatar: "",
  email: "",
  telephone: "",
  password: null,
});

const confirmPassword = ref("");
const confirmNewPassword = ref("");

const editInfo = ref(false);
const confirmPasswordVisible = ref(false);
const changePasswordVisible = ref(false);

// 计算属性：账户类型文本
const accountTypeText = computed(() => {
  const types: Record<number, string> = {
    0: "普通用户",
    1: "独立游戏开发者",
    2: "游戏开发商",
    3: "平台管理员",
  };
  return types[userInfo.value.accountType] || "未知类型";
});

// 格式化日期
function formatDate(dateString: string) {
  if (!dateString) return "未知";
  return dateString.replace("T", " ").substring(0, 16);
}

async function handleAvatarChange({ file }: any) {
  const formData = new FormData();
  formData.append("file", file);
  try {
    const { data } = await uploadApi(formData);
    ElMessage.success("头像上传成功！");
    newUserInfo.value.avatar = data;
    const res: any = await updateUserInfoApi(newUserInfo.value);
    if (res.code === 0) {
      userInfo.value.avatar = data;
      useTokenStore().setAvatar(data);
    }
  } catch (error) {
    console.log(error);
    ElMessage.error("头像上传失败！");
  }
}

async function getUserInfo() {
  try {
    const { data } = await getUserInfoApi();
    userInfo.value = { ...data };
    newUserInfo.value = { ...data };
    console.log(userInfo.value);
  } catch (error) {
    console.log(error);
    ElMessage.error("获取用户信息失败！");
  }
}

async function handleConfirmPassword(password: string) {
  const formData = new FormData();
  formData.append("password", password);
  try {
    const res: any = await confirmPasswordApi(formData);
    if (res.code === 0) {
      return true;
    } else {
      ElMessage.error("密码错误！");
      return false;
    }
  } catch (error) {
    ElMessage.error("请求异常！");
    return false;
  }
}

async function updateUserInfo() {
  try {
    if (await handleConfirmPassword(confirmPassword.value)) {
      const res: any = await updateUserInfoApi(newUserInfo.value);
      if (res.code === 0) {
        ElMessage.success("用户信息修改成功！");
        confirmPasswordVisible.value = false;
        editInfo.value = false;
        confirmPassword.value = "";
        await getUserInfo();
      } else {
        ElMessage.error("用户信息修改失败！");
      }
    }
  } catch (error) {
    ElMessage.error("请求异常！");
  }
}

async function changePassword() {
  if (!confirmPassword.value) {
    ElMessage.error("旧密码不能为空！");
    return;
  }

  if (!newUserInfo.value.password) {
    ElMessage.error("新密码不能为空！");
    return;
  }

  if (newUserInfo.value.password !== confirmNewPassword.value) {
    ElMessage.error("两次新密码输入不一致！");
    return;
  }

  if (newUserInfo.value.password === confirmPassword.value) {
    ElMessage.error("新密码不能与旧密码相同！");
    return;
  }

  try {
    if (await handleConfirmPassword(confirmPassword.value)) {
      console.log(newUserInfo.value);
      const res: any = await updateUserInfoApi(newUserInfo.value);
      if (res.code === 0) {
        ElMessage.success("密码修改成功，请重新登录！");
        confirmPasswordVisible.value = false;
        changePasswordVisible.value = false;
        confirmPassword.value = "";
        newUserInfo.value.password = null;
        confirmNewPassword.value = "";
        await logoutApi();
        useTokenStore().removeToken();
        router.replace("/login-register");
      } else {
        ElMessage.error("密码修改失败！");
      }
    }
  } catch (error) {
    ElMessage.error("请求异常！");
  }
}

onMounted(() => {
  getUserInfo();
});
</script>

<style scoped>
.user-center-container {
  margin: 0 auto;
}

.user-profile-card {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0;
}

.avatar-section .user-avatar {
  width: 150px;
  height: 150px;
  border-radius: 50%;
  margin-bottom: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.avatar-section .user-avatar :deep(.el-image__inner) {
  object-fit: cover;
}

.avatar-section .avatar-error {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  color: #909399;
  border-radius: 50%;
}

.avatar-section .avatar-uploader {
  margin-top: 10px;
}

.user-info-section {
  text-align: center;
  margin-bottom: 30px;
}

.user-info-section .user-name {
  font-size: 28px;
  margin-bottom: 15px;
  position: relative;
  display: inline-block;
  padding-right: 40px;
}

.user-info-section .user-name .edit-icon {
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  cursor: pointer;
  color: var(--el-color-primary);
  transition: color 0.3s;
}

.user-info-section .user-name .edit-icon:hover {
  color: var(--el-color-primary-light-3);
}

.user-info-section .user-meta {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 15px;
  margin-top: 10px;
}

.user-info-section .user-meta .meta-item {
  display: flex;
  align-items: center;
  color: #606266;
  font-size: 14px;
}

.user-info-section .user-meta .meta-item .el-icon {
  margin-right: 5px;
}

.account-card {
  margin-top: 20px;
  border: none;
}

.account-card .card-header {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: 500;
}

.account-card .card-header .el-icon {
  margin-right: 8px;
  color: var(--el-color-primary);
}

.account-card .account-info .info-item {
  display: flex;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px dashed var(--el-border-color);
}

.account-card .account-info .info-item:last-child {
  border-bottom: none;
}

.account-card .account-info .info-item .label {
  width: 80px;
  color: #909399;
  font-size: 14px;
}

.account-card .account-info .info-item .value {
  flex: 1;
  font-size: 15px;
}

.account-card .account-info .info-item .edit-icon {
  margin-left: 10px;
  cursor: pointer;
  color: var(--el-color-primary);
  transition: color 0.3s;
}

.account-card .account-info .info-item .edit-icon:hover {
  color: var(--el-color-primary-light-3);
}

.editInfo {
  display: flex;
  justify-content: center;
  align-items: center;
}

@media (max-width: 768px) {
  .user-center-container {
    padding: 10px;
  }

  .user-name {
    font-size: 24px !important;
  }

  .user-meta {
    flex-direction: column;
    align-items: center;
    gap: 8px !important;
  }
}
</style>
